using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Tavis.Tools {
    public class ServerException : Exception {

        private readonly HttpStatusCode _HttpStatusCode = HttpStatusCode.ServiceUnavailable; // If we get a response, this will be updated
        private readonly Uri _Url;

        private readonly ExceptionDetails _ExceptionDetails;

        public Uri Url {
            get { return _Url; }
        }

        public bool IsClientError { get; set; }

        public HttpStatusCode HttpStatusCode {
            get { return _HttpStatusCode; }
        }
        public ServerException(HttpResponseMessage response) : base("ServerException") {

            _Url = response.RequestMessage.RequestUri;
            _HttpStatusCode = response.StatusCode;
            IsClientError = response.HasClientErrorStatus();

            if (response.Content != null && response.Content.Headers.ContentType == new MediaTypeHeaderValue("application/vnd.tavis.exception+xml")) {
                _ExceptionDetails = response.Content.ReadAsExceptionDetails();
            } else {
                _ExceptionDetails = new ExceptionDetails() {
                                                                Message = response.StatusCode + " (" + (int)response.StatusCode + ")"
                                                           };
            }

        }

        public string Code {
            get {
                return _ExceptionDetails.Code;
            }
        }
        public override string Message {
            get {
                return _ExceptionDetails.Message;
            }
        }
    }

    public class ExceptionDetails {

        public string Code { get; set; }
        public string Message { get; set; }


    }


}
